import { h, ref, render } from "vue";

import subPageContainer from "./subPageContainer.vue";
import emitter from "@/utils/bus";
/**
 * 创建并渲染子页面实例
 *
 * @param {Object} appContext - 应用上下文
 * @param {VNode[]} slots - 插槽内容
 * @param {Object} properties - 子页面属性，包括标题、是否动作栏置顶等
 * @param {Function} callBack - 关闭子页面时的回调函数
 * @returns {VNode} - 渲染后的虚拟节点
 */
const subPageInstance = (appContext, slots, properties, callBack) => {
  const title = ref("");
  const actions = ref([]);
  const isActionTop = ref(false);
  const container = document.querySelector(".side-page-warp") || document.querySelector(".app-container");
  const close = (val) => {
    emitter.on("closeSubPage");
    render(null, container);
    callBack(val);
  };
  title.value = properties.title;
  isActionTop.value = properties.isActionTop;
  // 插槽设置容器 标题  按钮 关闭
  const _props = {
    onClose: (val) => close(val),
    onSetTitle: (val) => {
      title.value = val;
    },
    onSetActions: (val) => {
      actions.value = val;
    },
    onSetIsActionTop: (val) => {
      isActionTop.value = val;
    },
    ...properties,
  };

  // 1. 生成 vnode
  const vnode = h(
    subPageContainer,
    {
      title,
      actions,
      isActionTop,
      onClose: (val) => close(val),
    },
    {
      default: () => [h(slots, _props)],
    }
  );
  emitter.on("closeSubPage", () => close());
  vnode.appContext = appContext;
  // 2. render 渲染
  return render(vnode, container);
};

const install = (app) => {
  const instance = app._context;
  const subPage = (slots, properties, callBack = () => {}) => {
    return subPageInstance(instance, slots, properties, callBack);
  };
  app.config.globalProperties.subPageNext = subPage;
};
export default install;
